<?php

namespace app\admin\controller;

use app\admin\service\AccountService;
use app\models\AuthGroupAccessModel;
use app\models\AuthModel;
use app\models\CampusModel;
use app\models\CompanyModel;
use app\models\GradesDetailsModel;
use app\models\MemberModel;
use app\models\ParentInformationModel;
use app\models\RegionalModel;
use app\models\StudentModel;
use app\models\TeacherModel;
use app\models\UserModel;

/**
 * Class User.
 */
class User extends Common
{

    /**
     * 班级管理详情模型.
     *
     * @var GradesDetailsModel
     */
    protected $gradesdetailModel;

    /**
     * 学生信息模型.
     *
     * @var StudentModel
     */
    protected $studentModel;

    /**
     * 老师管理模型.
     *
     *  @var TeacherModel
     */
    protected $teacherModel;

    /**
     * 小程序用户管理模型.
     *
     * @var MemberModel
     */
    protected $memberModel;


    /**
     * 用户管理模型.
     *
     * @var UserModel
     */
    protected $userModel;

    /**
     * 用户组模型.
     *
     * @var AuthModel
     */
    protected $authModel;

    /**
     * 用户组与权限关系模型.
     *
     * @var AuthGroupAccessModel
     */
    protected $authGroupAccessModel;

    /**
     * 校区模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

	/**
	 * 区域模型
	 * @var RegionalModel
	 */
	protected $regionalModel;

	/**
	 * 集团模型
	 * @var CompanyModel
	 */
	protected $companyModel;

    /**
     * 系统用户管理.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
			if (2 === (int) input('p')) {
				return $this->uploadImg(); //处理上传图片
			}
            $param = $this->request->param();
            $campus = $this->userModel->getUserLists($param);
            $this->success('success', '', $campus, 0);
        }
        $type = get_current_type();
        $company = $this->companyModel->select();
        return $this->fetch('',['type' => $type, 'company' => $company]);
    }

    /**
     * 添加系统用户.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function add()
    {
		if ($this->request->isAjax() && $this->request->isPost()) {
			$_data = input('post.');
			$data['company_id'] = $_data['company_id'];
			$data['group_id'] = $_data['group_id'];
			$data['username'] = $_data['mobile'];
			$data['gender'] = $_data['gender'];
			$data['mobile'] = $_data['mobile'];
			$data['name'] = $_data['name'];
			$data['status_center'] = $_data['status_center'];//是否绑定个人中心0:未绑定,1:绑定
			$data['group_type'] = (new AuthModel())->get($_data['group_id'])['group_type'];
			$checkUsername = $this->userModel->get(['mobile'=>$_data['mobile']]);
			if($checkUsername){
				$this->error('手机号码已存在', null, '', 1);
			}
			$data['salt'] = md5(date('Y-m-d H:i:s'));
			$data['password'] = AccountService::encodePassword($_data['password'], $data['salt']);
			$data['wtype'] = 2;

            /***************同步数据*****************/
            $user_xt  = $this->userModel->get(['company_id' => $_data['company_id'],'wtype' => 2]);
            if($user_xt){
                $data['campus_id'] = $user_xt['campus_id'];  //校区
                $data['regional_id'] = $user_xt['regional_id'];  //区域
            }
            /*****************************************/
			$data['img'] = '/img.jpg';
            $user = $this->userModel->save($data);
			$uid = $this->userModel->id;
			if (!$user) {
				$this->error('添加用户失败', null, '', 1);
			}
			if (!empty($data['group_id'])) {
				$group = [
					'uid' => $uid,
					'group_id' => $data['group_id'],
				];
				$res = $this->authGroupAccessModel->where('uid', $uid)->find();
				if ($res) {
					$this->authGroupAccessModel->where('uid', $uid)->delete();
				}
				$this->authGroupAccessModel->save($group);
			}
			//是否绑定个人中心0:未绑定,1:绑定
			if($data['status_center'] == 1){
                $wx_date['mobile'] = $data['mobile'];
                $wx_date['password'] = $data['password'];
                $wx_date['salt'] = $data['salt'];
                $wx_date['company_id'] = $data['company_id'];
                $wx_date['auth_rules'] = $_data['auth_rules'];
                $wx_date['user_id'] = $uid;
                $wx_date['create_time'] = date('Y-m-d H:i:s');
                $wx_user = $this->memberModel->save($wx_date);
                if(!$wx_user){
                    $this->error('添加小程序用户失败', null, '', 1);
                }
            }
			$this->success('添加成功', url('User/lists'), '', 1);
		}
		$company = $this->companyModel->where(['status' => 1,'id' => input('company_id')])->field('id,company_name')->select();
		$where['type'] = 2;
		$where['status'] = 1;
		$where['id'] = ['neq',1];

        if(get_current_type() != 1){
            $where['company_id'] = get_current_company_id();
        }else{
            $where['company_id'] = input('company_id');
        }
		$groups = $this->authModel->where($where)->field('id,title')->select();
		return $this->fetch('', [
			'groups' => $groups,
			'company' => $company
		]);
    }

    /**
     * 编辑系统用户.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function edit()
    {
		if ($this->request->isAjax() && $this->request->isPost()) {
			$_data = input('post.');
			$data['company_id'] = $_data['company_id'];
			$data['group_id'] = $_data['group_id'];
			$data['username'] = $_data['mobile'];
			$data['gender'] = $_data['gender'];
			$data['mobile'] = $_data['mobile'];
			$data['name'] = $_data['name'];
			if ($_data['password']) {
				$data['salt'] = md5(date('Y-m-d H:i:s'));
				$data['password'] = AccountService::encodePassword($_data['password'], $data['salt']);
			} else {
				$data['password'] = $this->userModel->where('mobile', $data['mobile'])->value('password');
                $data['salt'] = $this->userModel->where('mobile', $data['mobile'])->value('salt');
			}
			$data['wtype'] = 2;
            $this->userModel->save($data, ['id' => $_data['id']]);
			$group = array(
				'uid' => $_data['id'],
				'group_id' => $data['group_id'],
			);
			$checkId = $this->authGroupAccessModel->get(['uid'=>$_data['id']]);
			if ($checkId) {
				$this->authGroupAccessModel->where('uid', $_data['id'])->delete();
			}
			$this->authGroupAccessModel->save($group);

            $res = $this->userModel->get($_data['id']);
            if($_data['status_center'] == 0 && $res['status_center'] == 1){
                if(!$this->memberModel->where(['mobile' => $res['mobile']])->delete()){
                    $this->error('解绑小程序失败', null, '', 1);
                }
                if(!$this->userModel->where(['id' => $_data['id']])->update(['status_center' => 0])){
                    $this->error('更新小程序状态失败', null, '', 1);
                }
            }else if($_data['status_center'] == 1 && $res['status_center'] == 0){
                $wx_date['mobile'] = $data['mobile'];
                $wx_date['password'] = $data['password'];
                $wx_date['salt'] = $data['salt'];
                $wx_date['company_id'] = $data['company_id'];
                $wx_date['auth_rules'] = $_data['auth_rules'];
                $wx_date['user_id'] = $_data['id'];
                $wx_date['create_time'] = date('Y-m-d H:i:s');
                $wx_user = $this->memberModel->save($wx_date);
                if(!$wx_user){
                    $this->error('添加小程序用户失败', null, '', 1);
                }
                if(!$this->userModel->where(['id' => $_data['id']])->update(['status_center' => 1])){
                    $this->error('更新小程序状态失败', null, '', 1);
                }
            }else if($_data['status_center']  == 1 && $res['status_center'] == 1){
                $this->memberModel->where(['user_id' => $_data['id']])->update(['company_id' => $data['company_id'], 'password' => $data['password'], 'salt' => $data['salt'], 'auth_rules' => $_data['auth_rules'], 'mobile' => $data['mobile']]);
            }
			$this->success('编辑成功', url('User/lists'), '', 1);
		}
		// 获取用户数据
		$user = $this->userModel->get(input('id'));
		$auth_rules = '';
		if($user['status_center'] == 1){
            $auth_rules = $this->memberModel->get(['mobile' => $user['mobile'],'company_id' => $user['company_id']])['auth_rules'];
        }
		// 获取已加入用户组
		$group_access = $this->authGroupAccessModel->where('uid', input('id'))->value('group_id');
		// 获取所有用户组
		$where['type'] = 2;
		$where['status'] = 1;
		$where['id'] = ['neq',1];
		$groups = $this->authModel->where($where)->field('id,title')->select();
		$company = $this->companyModel->where(['status' => 1])->field('id,company_name')->select();
		return $this->fetch('', [
			'groups' => $groups,
			'company' => $company,
			'group_access' => $group_access,
			'user' => $user,
            'auth_rules' => $auth_rules
		]);
    }

	/**
	 * 删除系统用户.
	 *
	 * @return mixed
	 */
	public function del()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {

		    $res = $this->userModel->get(['id' => input('id')]);


		    if($res['status_center'] == 1){
                if(!$this->memberModel->where(['mobile' => $res['mobile']])->delete()){
                    $this->error('删除小程序用户失败', null, '', 1);
                }
            }



			if (!$this->userModel->where(['id' => input('id')])->delete()) {
				$this->error('删除用户失败', null, '', 1);
			}


			$this->success('删除成功', url('User/lists'), '', 1);
		}
	}

	/**
	 * 区域用户管理.
	 *
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function regional()
	{
		if ($this->request->isAjax()) {
			$param = $this->request->param();
			$param['wtype'] = 3;
			$campus = $this->userModel->getRegionalUserLists($param);
			$this->success('success', '', $campus, 0);
		}

		return $this->fetch('',['type'=>get_current_type(),'company_id'=>get_current_company_id()]);
	}

	/**
	 * 添加区域用户.
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function add_regional()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$_data = input('post.');
			$_data['regional_id'] = array_unique($_data['regional_id']);  //去重
            $data['company_id'] = $_data['company_id']; //集团ID
			$data['regional_id'] = implode(',',$_data['regional_id']);
			$campus_id = $this->campusModel->where(['regional_id'=>['in',$data['regional_id']]])->column('id');
			if (!$campus_id) {
				$this->error('该区域暂无校区，请先添加校区', null, '', 1);
			}
			$regional_name = $this->regionalModel->where(['id'=>['in',$data['regional_id']]])->column('regional_name');
			$data['regional_name'] = implode(',',$regional_name);
			$data['campus_id'] = implode(',',$campus_id);
			$data['group_id'] = $_data['group_id'];
			$data['username'] = $_data['mobile'];
			$data['gender'] = $_data['gender'];
			$data['mobile'] = $_data['mobile'];
            $data['status_center'] = $_data['status_center'];
			$data['name'] = $_data['name'];
            $data['group_type'] = (new AuthModel())->get($_data['group_id'])['group_type'];
			$checkUsername = $this->userModel->get(['mobile'=>$_data['mobile']]);
			if($checkUsername){
				$this->error('用户已存在', null, '', 1);
			}
			$data['salt'] = md5(date('Y-m-d H:i:s'));
			$data['password'] = AccountService::encodePassword($_data['password'], $data['salt']);
			$data['wtype'] = 3;
			$data['img'] = '/img.jpg';
			$user = $this->userModel->save($data);
			$uid = $this->userModel->id;
			$this->updateCompanyCampus();
			if (!$user) {
				$this->error('添加用户失败', null, '', 1);
			}
			if (!empty($data['group_id'])) {
				$group = [
					'uid' => $uid,
					'group_id' => $data['group_id'],
				];
				$res = $this->authGroupAccessModel->where('uid', $uid)->find();
				if ($res) {
					$this->authGroupAccessModel->where('uid', $uid)->delete();
				}
				$this->authGroupAccessModel->save($group);
			}

            if($data['status_center'] == 1){
                $wx_date['mobile'] = $data['mobile'];
                $wx_date['password'] = $data['password'];
                $wx_date['salt'] = $data['salt'];
                $wx_date['company_id'] = $data['company_id'];
                $wx_date['auth_rules'] = $_data['auth_rules'];
                $wx_date['user_id'] = $uid;
                $wx_date['create_time'] = date('Y-m-d H:i:s');
                $wx_user = $this->memberModel->save($wx_date);
                if(!$wx_user){
                    $this->error('添加小程序用户失败', null, '', 1);
                }
            }
			$this->success('添加成功', url('User/lists'), '', 1);
		}
		$where_regional = [];
		$where = [];
		if(get_current_type() != 1){
			$where_regional['company_id'] = get_current_company_id();
		}else{
            $where_regional['company_id'] = input('company_id');
        }
		$where_regional['status'] = 1;
		$regional = $this->regionalModel->where($where_regional)->field('id,regional_name')->select();
		$where['type'] = 3;
		$where['status'] = 1;
        $where['company_id'] = $where_regional['company_id'];
		$groups = $this->authModel->where($where)->field('id,title')->select();
		return $this->fetch('', [
		    'company_id' => $where_regional['company_id'],
			'groups' => $groups,
			'regional' => $regional,
			'type' => get_current_type(),
		]);
	}

	/**
	 * 编辑区域用户.
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
    public function edit_regional()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
			$_data = input('post.');
			$data['company_id'] = $this->userModel->get(['id' => $_data['id']])['company_id'];
			$data['regional_id'] = implode(',',$_data['regional_id']);
			$campus_id = $this->campusModel->where(['regional_id'=>['in',$data['regional_id']]])->column('id');
			if (!$campus_id) {
				$this->error('该区域暂无校区，请先添加校区', null, '', 1);
			}
			$regional_name = $this->regionalModel->where(['id'=>['in',$data['regional_id']]])->column('regional_name');
			$data['regional_name'] = implode(',',$regional_name);
			$data['campus_id'] = implode(',',$campus_id);
			$data['group_id'] = $_data['group_id'];
			$data['company_id'] = $data['company_id'];
			$data['username'] = $_data['mobile'];
			$data['gender'] = $_data['gender'];
			$data['mobile'] = $_data['mobile'];
			$data['name'] = $_data['name'];
            if ($_data['password']) {
                $data['salt'] = md5(date('Y-m-d H:i:s'));
                $data['password'] = AccountService::encodePassword($_data['password'], $data['salt']);
            } else {
                $data['salt'] = $this->userModel->where('mobile', $data['mobile'])->value('salt');
                $data['password'] = $this->userModel->where('mobile', $data['mobile'])->value('password');
            }
			$data['wtype'] = 3;
			$this->updateCompanyCampus();
            $this->userModel->save($data, ['id' => $_data['id']]);
            $group = array(
                'uid' => $_data['id'],
                'group_id' => $data['group_id'],
            );
            $checkId = $this->authGroupAccessModel->get(['uid'=>$_data['id']]);
            if ($checkId) {
                $this->authGroupAccessModel->where('uid', $_data['id'])->delete();
            }
            $this->authGroupAccessModel->save($group);

            $res = $this->userModel->get(['id' => $_data['id']]);
            if($_data['status_center']  == 0 && $res['status_center'] == 1){
                if(!$this->memberModel->where(['mobile' => $res['mobile']])->delete()){
                    $this->error('解绑小程序失败', null, '', 1);
                }
                if(!$this->userModel->where(['id' => $_data['id']])->update(['status_center' => 0])){
                    $this->error('更新小程序状态失败', null, '', 1);
                }

            }else if($_data['status_center']  == 1 && $res['status_center'] == 0){
                $wx_date['mobile'] = $data['mobile'];
                $wx_date['password'] = $data['password'];
                $wx_date['salt'] = $data['salt'];
                $wx_date['company_id'] = $data['company_id'];
                $wx_date['auth_rules'] = $_data['auth_rules'];
                $wx_date['user_id'] = $_data['id'];
                $wx_date['create_time'] = date('Y-m-d H:i:s');
                $wx_user = $this->memberModel->save($wx_date);
                if(!$wx_user){
                    $this->error('添加小程序用户失败', null, '', 1);
                }
                if(!$this->userModel->where(['id' => $_data['id']])->update(['status_center' => 1])){
                    $this->error('更新小程序状态失败', null, '', 1);
                }

            }else if($_data['status_center']  == 1 && $res['status_center'] == 1){
                $this->memberModel->where(['user_id' => $_data['id']])->update(['company_id' => $data['company_id'], 'password' => $data['password'], 'salt' => $data['salt'], 'auth_rules' => $_data['auth_rules'], 'mobile' => $data['mobile']]);
            }

            $this->success('编辑成功', url('User/lists'), '', 1);
        }

        // 获取用户数据
        $user = $this->userModel->get(input('id'));

        $auth_rules = '';
        if($user['status_center'] == 1){
            $auth_rules = $this->memberModel->get(['mobile' => $user['mobile'], 'company_id' => $user['company_id']])['auth_rules'];
        }
        // 获取已加入用户组
        $group_access = $this->authGroupAccessModel->where('uid', input('id'))->value('group_id');
        // 获取所有用户组
		$where_regional = [];
		$where = [];
		if(get_current_type() != 1){
		    $where['company_id'] = get_current_company_id();
			$where_regional['company_id'] = get_current_company_id();
		}else{
            $where['company_id'] = $user['company_id'];
            $where_regional['company_id'] = $user['company_id'];
        }
		$where_regional['status'] = 1;
		$regional = $this->regionalModel->where($where_regional)->field('id,regional_name')->select();
		$where['type'] = 3;
		$where['status'] = 1;
		$groups = $this->authModel->where($where)->field('id,title')->select();
        return $this->fetch('', [
            'groups' => $groups,
			'regional' => $regional,
            'group_access' => $group_access,
            'user' => $user,
			'type' => get_current_type(),
            'auth_rules' => $auth_rules
        ]);
    }

	/**
	 * 更新当前集团的校区、区域ID
	 * modify by Small Y
	 *
	 */
    function updateCompanyCampus()
	{
		$update_where = [];
		$update_data = [];
		//操作添加、编辑区域更新集团内的区域和校区ID
		$update_where['company_id'] = get_current_company_id();
		$update_where['wtype'] = 2;
		$campusIds = $this->userModel->where(['company_id'=>get_current_company_id(),'wtype'=>['neq',2]])->group('campus_id')->column('campus_id');
		$regionalIds = $this->userModel->where(['company_id'=>get_current_company_id(),'wtype'=>['neq',2]])->group('regional_id')->column('regional_id');
		$campusIdStr = implode(',',$campusIds);
		$campusIdArr = explode(',',$campusIdStr);
		$regionalIdStr = implode(',',$regionalIds);
		$regionalIdArr = explode(',',$regionalIdStr);
		$cidArr = array_unique($campusIdArr);
		$ridArr = array_unique($regionalIdArr);
		$cidStr = implode(',',$cidArr);
		$ridStr = implode(',',$ridArr);
		$update_data['campus_id'] = $cidStr;
		$update_data['regional_id'] = $ridStr;
		$this->userModel->where($update_where)->update($update_data);
	}

	/**
	 * 删除区域用户.
	 *
	 * @return mixed
	 */
	public function del_regional()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
            $res = $this->userModel->get(['id' => input('id')]);

            if($res['status_center'] == 1){
                if(!$this->memberModel->where(['mobile' => $res['mobile']])->delete()){
                    $this->error('删除小程序用户失败', null, '', 1);
                }
            }

			if (!$this->userModel->where(['id' => input('id')])->delete()) {
				$this->error('删除用户失败', null, '', 1);
			}
			$this->success('删除成功', url('User/lists'), '', 1);
		}
	}

	/**
	 * 校区用户管理.
	 *
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function campus()
	{
		if ($this->request->isAjax()) {
			if(input('p') == 1){
				return $this->getCampus();
			}
			$param = $this->request->param();
			if(get_current_type() == 4 && get_current_type() != 5){
				$param['wtype'] = 5;
			}else if(get_current_type() != 4 && get_current_type() != 5){
				$param['wtype'] = array('in','4,5');
			}
			$campus = $this->userModel->getCampusUserLists($param);
			$this->success('success', '', $campus, 0);
		}

		$type = get_current_type();
		return $this->fetch('',['type' => $type]);
	}

	/**
	 * 获取校区
	 * modify by Small Y
	 *
	 */
	private function getCampus()
	{
		$where = array(
			'regional_id' => input('regional_id'),
			'status' => 1,
		);
		return $this->campusModel->where($where)->select();
	}

	/**
	 * 添加校区用户.
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function add_campus()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$auth_rules = $data['auth_rules'];

            $data['group_type'] = AuthModel::get(['id' => $data['group_id']])['group_type'];
            $checkUsername = '';
			if($data['group_type'] == 3 || $data['group_type'] == 2){
                $checkUsername = $this->userModel->get(['name'=>$data['name'],'mobile' => $data['mobile'],'group_type' => $data['group_type']]);
                if(!$checkUsername){
                    $checkUsername = $this->userModel->get(['mobile'=>$data['mobile']]);
                }
            }else{
                $checkUsername = $this->userModel->get(['mobile'=>$data['mobile']]);
            }
			if($checkUsername){
				$this->error('用户已存在', null, '', 1);
			}
			$data['salt'] = md5(date('Y-m-d H:i:s'));
			$data['password'] = AccountService::encodePassword($data['password'], $data['salt']);
			if(get_current_type() == 4){
				$data['wtype'] = 5;
				$data['regional_id'] = get_current_regional_id();
				$data['regional_name'] = RegionalModel::get(get_current_regional_id())['regional_name'];
			}else{
				$data['wtype'] = AuthModel::get(['id' => $data['group_id']])['type'];
				$data['regional_name'] = RegionalModel::get($data['regional_id'])['regional_name'];
				$data['campus_name'] = CampusModel::get($data['campus_id'])['campus_name'];
			}

            $data['company_id'] = $data['company_id'];

            unset($data['ids']);
            unset($data['auth_rules']);
			$data['img'] = '/img.jpg';
			$user = $this->userModel->save($data);
			$uid = $this->userModel->id;
			if (!$user) {
				$this->error('添加用户失败', null, '', 1);
			}else{
			    if($data['group_type'] == 2){  //老师类
                    //更新班级表的user_teacher_id
                    $this->gradesdetailModel->where(['teacher_id' => $data['teacher_id']])->update(['user_teacher_id' => $uid]);
                }else if($data['group_type'] == 3){  //助教类
                    //更新班级表的user_assistant_id
                    $this->gradesdetailModel->where(['assistant_id' => $data['teacher_id']])->update(['user_assistant_id' => $uid]);
                }
            }

			if (!empty($data['group_id'])) {
				$group = [
					'uid' => $uid,
					'group_id' => $data['group_id'],
				];
				$res = $this->authGroupAccessModel->where('uid', $uid)->find();
				if ($res) {
					$this->authGroupAccessModel->where('uid', $uid)->delete();
				}
				$this->authGroupAccessModel->save($group);
			}

            if($data['status_center'] == 1){
                $wx_date['mobile'] = $data['mobile'];
                $wx_date['password'] = $data['password'];
                $wx_date['salt'] = $data['salt'];
                $wx_date['company_id'] = $data['company_id'];
                $wx_date['auth_rules'] = $auth_rules;
                $wx_date['user_id'] = $uid;
                $wx_date['create_time'] = date('Y-m-d H:i:s');
                $wx_user = $this->memberModel->save($wx_date);
                if(!$wx_user){
                    $this->error('添加小程序用户失败', null, '', 1);
                }
            }
			$this->success('添加成功', url('User/lists'), '', 1);
		}
		$regional_where = [];
		$where = [];
		if(get_current_type() == 4){
			$campus = $this->campusModel->get(get_current_campus_id());
			$where['type'] = 5;
		}else{
			$campus = '';
			$where['type'] = array('in','4,5');
		}
		if(get_current_type() != 1){
            $where['company_id'] = get_current_company_id();
            $regional_where['company_id'] = get_current_company_id();
        }else if(get_current_type() == 1){
            $where['company_id'] = input('company_id');
            $regional_where['company_id'] = input('company_id');
        }

        if(get_current_type() == 3){  //区域
            $regional_where['id'] = get_current_regional_id();
        }
        $regional_where['status'] = 1;
        $where['status'] = 1;
		$regional = $this->regionalModel->where($regional_where)->field('id,regional_name,company_id')->select();
        $Last_group = -1;
		$groups = $this->authModel->where($where)->field('id,title,group_type')->select();
        if(count($groups) > 0){
            $Last_group = $groups[count($groups)-1]['group_type'];
        }
        $campus_res = $this->campusModel->where(['company_id'=> $where['company_id']])->column('id');
        if(get_current_type() == 4){
            $campus_str = get_current_campus_id();
        }else{
            $campus_str = implode(',',$campus_res);
        }
        $teachers = $this->teacherModel->where(['campus_id' => array('in',$campus_str)])->select();
		return $this->fetch('', [
			'groups' => $groups,
			'Last_group' => $Last_group,
			'campus' => $campus,
			'regional' => $regional,
			'teachers' => $teachers,
			'company_id' => $where['company_id'],
			'type'=>get_current_type()
		]);
	}

	/**
	 * 编辑校区用户.
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function edit_campus()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');

			$status_center = $data['status_center'];
			$auth_rules = $data['auth_rules'];

			if ($data['password']) {
				$data['salt'] = md5(date('Y-m-d H:i:s'));
				$data['password'] = AccountService::encodePassword($data['password'], $data['salt']);
			} else {
                $data['salt'] = $this->userModel->where('mobile', $data['mobile'])->value('salt');
				$data['password'] = $this->userModel->where('mobile', $data['mobile'])->value('password');
			}
			if(get_current_type() == 4){
				$data['wtype'] = 5;
				$data['regional_id'] = get_current_regional_id();
				$data['regional_name'] = RegionalModel::get(get_current_regional_id())['regional_name'];
			}else{
				$data['wtype'] = AuthModel::get(['id' => $data['group_id']])['type'];
				$data['regional_name'] = RegionalModel::get($data['regional_id'])['regional_name'];
				$data['campus_name'] = CampusModel::get($data['campus_id'])['campus_name'];
			}
			$data['company_id'] = $this->userModel->get(['id' => $data['id']])['company_id'];

			unset($data['status_center']);
            unset($data['auth_rules']);
            unset($data['ids']);
			$this->userModel->save($data, ['id' => $data['id']]);
			$group = array(
				'uid' => $data['id'],
				'group_id' => $data['group_id'],
			);
			$checkId = $this->authGroupAccessModel->get(['uid'=>$data['id']]);
			if ($checkId) {
				$this->authGroupAccessModel->where('uid', $data['id'])->delete();
			}
			$this->authGroupAccessModel->save($group);

            $res = $this->userModel->get(['id' => $data['id']]);
            if($status_center  == 0 && $res['status_center'] == 1){
                if(!$this->memberModel->where(['mobile' => $res['mobile']])->delete()){
                    $this->error('解绑小程序失败', null, '', 1);
                }
                if(!$this->userModel->where(['id' => $data['id']])->update(['status_center' => 0])){
                    $this->error('更新小程序状态失败', null, '', 1);
                }

            }else if($status_center  == 1 && $res['status_center'] == 0){

                $wx_date['mobile'] = $data['mobile'];
                $wx_date['password'] = $data['password'];
                $wx_date['salt'] = $data['salt'];
                $wx_date['company_id'] = $data['company_id'];
                $wx_date['auth_rules'] = $auth_rules;
                $wx_date['user_id'] = $data['id'];
                $wx_date['create_time'] = date('Y-m-d H:i:s');
                $wx_user = $this->memberModel->save($wx_date);
                if(!$wx_user){
                    $this->error('添加小程序用户失败', null, '', 1);
                }
                if(!$this->userModel->where(['id' => $data['id']])->update(['status_center' => 1])){
                    $this->error('更新小程序状态失败', null, '', 1);
                }

            }else if($status_center  == 1 && $res['status_center'] == 1){
                $this->memberModel->where(['user_id' => $data['id']])->update(['company_id' => $data['company_id'], 'password' => $data['password'], 'salt' => $data['salt'], 'auth_rules' => $auth_rules, 'mobile' => $data['mobile']]);
            }

			$this->success('编辑成功', url('User/lists'), '', 1);
		}

		// 获取用户数据
		$user = $this->userModel->get(input('id'));
        $auth_rules = '';
        if($user['status_center'] == 1){
            $auth_rules = $this->memberModel->get(['mobile' => $user['mobile'], 'company_id' => $user['company_id']])['auth_rules'];
        }
		// 获取已加入用户组
		$group_access = $this->authGroupAccessModel->where('uid', input('id'))->value('group_id');

		$regional_where = [];
		$where = [];
		if(get_current_type() == 4){
			$campus = $this->campusModel->get(get_current_campus_id());
			$where['type'] = 5;
		}else{
			$campus = '';
            $where['type'] = array('in','4,5');
		}
        if(get_current_type() != 1){
            $where['company_id'] = get_current_company_id();
            $regional_where['company_id'] = get_current_company_id();
        }else{
            $where['company_id'] = $user['company_id'];
            $regional_where['company_id'] = $user['company_id'];
        }

		$where['status'] = 1;
        $regional_where['status'] = 1;
		$groups = $this->authModel->where($where)->field('id,title')->select();
		$regional = $this->regionalModel->where($regional_where)->field('id,regional_name')->select();
		return $this->fetch('', [
			'groups' => $groups,
			'campus' => $campus,
			'regional' => $regional,
			'group_access' => $group_access,
			'user' => $user,
			'type' => get_current_type(),
            'auth_rules' => $auth_rules
		]);
	}

	/**
	 * 删除校区用户.
	 *
	 * @return mixed
	 */
	public function del_campus()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {

            $res = $this->userModel->get(['id' => input('id')]);

            if($res['status_center'] == 1){
                if(!$this->memberModel->where(['mobile' => $res['mobile']])->delete()){
                    $this->error('删除小程序用户失败', null, '', 1);
                }
            }

            if (!$this->userModel->where(['id' => input('id')])->delete()) {
				$this->error('删除用户失败', null, '', 1);
			}
			$this->success('删除成功', url('User/lists'), '', 1);
		}
	}

    /**
     * 密码重置.
     */
    public function campus_user_reset()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $password = '123456';
            $data['salt'] = md5(date('Y-m-d H:i:s'));
            $data['password'] = AccountService::encodePassword($password, $data['salt']);

            $res = $this->userModel->get(['id' => $data['id']]);
            $mobile = $res['mobile'];


            if($res['status_center']  == 1){
                $result = $this->memberModel->where(['mobile' => $mobile])->update(['salt' => $data['salt'],'password' => $data['password']]);
                if(!$result){
                    $this->error('小程序密码重置失败', null, '', 1);
                }
            }


            if (!$this->userModel->save($data, ['id' => $data['id']])) {
                $this->error('密码重置失败', null, '', 1);
            }
            $this->success('密码重置成功，密码为123456', '', '', 1);
        }
    }

    /**
     * 更改状态.
     *
     * @return mixed
     */
    public function campus_user_status()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (1 == $data['status']) {
                $msg = '启用';
            } else {
                $msg = '禁用';
            }

            $res = $this->userModel->get(['id' =>  $data['id']]);

            if($res['status_center'] == 1){
                $result = $this->memberModel->where(['mobile' => $res['mobile']])->update(['status' => $data['status']]);
                if(!$result){
                    $this->error($msg.'小程序失败', null, '', 1);
                }
            }

            if (!$this->userModel->save($data, ['id' => $data['id']])) {
                $this->error($msg.'失败', null, '', 1);
            }
            $this->success($msg.'成功', '', '', 1);
        }
    }

	/**
	 * 密码重置.
	 */
	public function regional_user_reset()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$password = '123456';
			$data['salt'] = md5(date('Y-m-d H:i:s'));
			$data['password'] = AccountService::encodePassword($password, $data['salt']);

            $res = $this->userModel->get(['id' => $data['id']]);
            $mobile = $res['mobile'];


            if($res['status_center']  == 1){
                $result = $this->memberModel->where(['mobile' => $mobile])->update(['salt' => $data['salt'],'password' => $data['password']]);
                if(!$result){
                    $this->error('小程序密码重置失败', null, '', 1);
                }
            }


            if (!$this->userModel->save($data, ['id' => $data['id']])) {
				$this->error('密码重置失败', null, '', 1);
			}
			$this->success('密码重置成功，密码为123456', '', '', 1);
		}
	}

	/**
	 * 更改状态.
	 *
	 * @return mixed
	 */
	public function regional_user_status()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			if (1 == $data['status']) {
				$msg = '启用';
			} else {
				$msg = '禁用';
			}

            $res = $this->userModel->get(['id' =>  $data['id']]);

            if($res['status_center'] == 1){
                $result = $this->memberModel->where(['mobile' => $res['mobile']])->update(['status' => $data['status']]);
                if(!$result){
                    $this->error($msg.'小程序失败', null, '', 1);
                }
            }

			if (!$this->userModel->save($data, ['id' => $data['id']])) {
				$this->error($msg.'失败', null, '', 1);
			}
			$this->success($msg.'成功', '', '', 1);
		}
	}

	/**
	 * 密码重置.
	 */
	public function user_reset()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$password = '123456';
			$data['salt'] = md5(date('Y-m-d H:i:s'));
			$data['password'] = AccountService::encodePassword($password, $data['salt']);

			$res = $this->userModel->get(['id' => $data['id']]);
			$mobile = $res['mobile'];


			if($res['status_center']  == 1){
                $result = $this->memberModel->where(['mobile' => $mobile])->update(['salt' => $data['salt'],'password' => $data['password']]);
                if(!$result){
                    $this->error('小程序密码重置失败', null, '', 1);
                }
            }


			if (!$this->userModel->save($data, ['id' => $data['id']])) {
				$this->error('密码重置失败', null, '', 1);
			}
			$this->success('密码重置成功，密码为123456', '', '', 1);
		}
	}

	/**
	 * 更改状态.
	 *
	 * @return mixed
	 */
	public function user_status()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			if (1 == $data['status']) {
				$msg = '启用';
			} else {
				$msg = '禁用';
			}

			$res = $this->userModel->get(['id' =>  $data['id']]);

			if($res['status_center'] == 1){
                $result = $this->memberModel->where(['mobile' => $res['mobile']])->update(['status' => $data['status']]);
                if(!$result){
                    $this->error($msg.'小程序失败', null, '', 1);
                }
            }

			if (!$this->userModel->save($data, ['id' => $data['id']])) {
				$this->error($msg.'失败', null, '', 1);
			}
			$this->success($msg.'成功', '', '', 1);
		}
	}


    /**
     * 选择集团
     * modify by Small Y
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function company()
    {
        if ($this->request->isAjax()) {
            $company_id = input('company_id');
            $status = input('status');
            if($status == 1){
                $title = '新增区域用户';
                $this->success('success', url('User/add_regional', ['company_id' => $company_id]), $title, 0);
            }

            if($status == 2){
                $title = '新增集团用户';
                $this->success('success', url('User/add', ['company_id' => $company_id]), $title, 0);
            }

            if($status == 3){
                $title = '新增校区用户';
                $this->success('success', url('User/add_campus', ['company_id' => $company_id]), $title, 0);
            }

        }
        $where = [];
        $where['status'] = 1;
        $status = input('status');  //来源
        /*************过滤掉未分配系统账号的集团*************/
        if(get_current_type() == 1 && $status != 2){
            $user_result = $this->userModel->where(['wtype' => 2])->select();
            $company_user_arr = [];
            foreach ($user_result as $key => $value){
                $company_user_arr[] = $value['company_id'];
            }
            $company_user_arr = array_unique($company_user_arr);
            $company_user_str = implode(',',$company_user_arr);
            $where['id'] = ['in',$company_user_str];
        }

        $company = $this->companyModel->where($where)->select();



        return $this->fetch('', [
            'company' => $company,
            'status' => $status
        ]);
    }

    /**************家长****************/
	/**
	 * 家长用户列表
	 * User: wufeng
	 * Date: 2020/03/23
	 *
	 * @return false|mixed|\PDOStatement|string|\think\Collection
	 * @throws \think\exception\DbException
	 */
	public function parent()
	{
		if ($this->request->isAjax()) {
			$params = $this->request->param();
			$parentInformation = (new ParentInformationModel())->getParentInformationLists($params);
			$this->success('success', '', $parentInformation, 0);
		}

		return $this->fetch();
	}

	/**
	 * 家长状态
	 * User: wufeng
	 * Date: 2020/03/23
	 *
	 */
	public function parent_status()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$msg = '';
			if (1 == $data['status']) {
				$msg = '启用';
			} else {
				$msg = '禁用';
			}
			$res = (new ParentInformationModel())->save($data, ['id' => $data['id']]);
			if ($res !== false) {
				$this->success($msg.'成功', '', '', 1);
			}
			$this->error($msg.'失败', null, '', 1);
		}
	}

	/**
	 * 密码重置
	 * User: wufeng
	 * Date: 2020/03/23
	 *
	 */
	public function parent_reset()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$password = '123456';
			$data['salt'] = md5(date('Y-m-d H:i:s'));
			$data['password'] = AccountService::encodePassword($password, $data['salt']);
			$res = (new ParentInformationModel())->save($data, ['id' => $data['id']]);
			if ($res !== false) {
				$this->success('密码重置成功，密码为123456', '', '', 1);
			}
			$this->error('密码重置失败', null, '', 1);
		}
	}

	/**************家长****************/

    /**
     * 获取校区教务/学管师
     * modify by Small Y
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByCampusEduUser(){
        $campusId = input('campus_id');
        if ($campusId) {
            $users = $this->userModel->where(['campus_id' => $campusId, 'group_type' => 5])->field('id,name')->select()->toArray(); //获取教务人员
            if(get_current_type() != 5){
                $arr[] = [
                    'id' => get_current_id(),
                    'name' => get_current_name(),
                ];
                $users = array_merge($users, $arr);
            }
            $this->success('success', '', $users, 0);
        }
        $this->error('无数据');
    }

	/**
	 * 上传头像页面
	 * User: wufeng
	 * Date: 2019/6/3
	 *
	 * @return \think\response\View
	 * @throws \think\exception\DbException
	 */
    public function upload_img()
	{
		if (request()->isPost()) {
			try {
				$data = input('post.');
				unset($data['file']);
				(new UserModel())->update($data);
				return ['code' => 0, 'msg' => '操作成功'];
			} catch (\Exception $ex) {
				return ['code' => 1, 'msg' => $ex->getMessage()];
			}
		}
		$user = (new UserModel())->get(input('id'));
		$user['img'] = $user['img'] ? $user['img'] : '/img.jpg';
		$this->assign('user', $user);
		return view();
	}

	/**
	 * 上传头像
	 * User: wufeng
	 * Date: 2019/6/4
	 *
	 * @param $id
	 */
	private function uploadImg()
	{
		$file = $_FILES;
		$path = UPLOAD_PATH.DS.'headimg'.DS;
		// 自定义文件上传路径
        if (!is_dir($path)) {
			mkdir($path,777,true);
		}
		$_filePath = '/uploads/headimg/'.$file['file']['name'];
		$res = fileUpload($file, $path);
		$res['url'] = str_replace('\\', '/', $_filePath);
		if (0 === (int)$res['code']) {
			$this->error($res['msg'], null, '', 1);
		}
		$this->success($res['msg'], '', $res['url'], 1);
	}

    /**
     *  实例化.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->userModel = new UserModel();
        $this->authModel = new AuthModel();
        $this->campusModel = new CampusModel();
        $this->authGroupAccessModel = new AuthGroupAccessModel();
        $this->regionalModel = new RegionalModel();
        $this->companyModel = new CompanyModel();
        $this->teacherModel = new TeacherModel();
        $this->studentModel = new StudentModel();
        $this->gradesdetailModel = new GradesDetailsModel();
        $this->memberModel = new MemberModel();
    }
}
